<template>
  <s-layout id="layout" :title="'借支审批'" navbar="normal" leftIconColor="#333" :autoBack="false" :bgColor="state.bgColor"
    :tabbarshow='false' :titleStyle="{ color: '#333', fontSize: '32rpx' }">
    <view class="call_on list_box" :style="{ paddingTop: (safeAreaInsets?.top + 44) + 'px' }">
      <fui-tabs :tabs="state.menulist" scroll @change="menulistclick"></fui-tabs>
      <scroll-view scroll-y class="comprehensive" v-if="list.length" @scrolltolower='listScrolltolower'
        show-scrollbar="true" :refresher-enabled="isOpenRefresh" :refresher-triggered="triggered"
        :refresher-threshold="100" refresher-background="white" @refresherpulling="onPulling"
        @refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort" @scroll="onScroll" :style="state.status == '0,3' ? 'height:68vh' : 'height:82vh'">
        <view class="item_wrap">
          <view class="item" v-for="(item, index) in list" :key="index">
            <view class="flex">

              <view class="select_box">
                <view class="select_image"  @tap="moreSelect(item)" v-if="state.status == '0,3'">
                  <!-- v-if="bottomset == true" -->
                  <image :src=" item.is_selected  ? `${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_check.png` : `${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_checkfor.png`" mode="scaleToFill"/>
                </view>
                <image class="flex_img" :src="`${baseUrl}/uploads/uniapp_image/staff/shenpi_icon2.png`" mode="scaleToFill" />
              </view>
              
              <view class="item_left">
                <view class="item_left_box">
                  <view :class="state.arrclass[item.state]">
                    {{ item.state_text }}
                  </view>
                  <view class="title">{{ item.user.nickname }}提交的借支</view>
                </view>
                <view class="item_left_box">
                  <text class="name">借支事由： {{ item.title }}</text>
                </view>
                <view class="item_left_box">
                  <text class="name">提交时间： {{ formatDate(item.createtime) }}</text>
                </view>
                <view class="item_left_box">
                  <view class="time_money">借支金额</view>
                  <text class="time_name">￥{{ item.price }}</text>
                </view>
              </view>
              <view class="item_right" @click="lookDetail(item)">
                <text class="name">查看详情</text>
                <u-icon size="10" name="arrow-right" color="#0038F7"></u-icon>
              </view>
            </view>

          <view v-if="item.level == userInfo.id">
              <view class="buttons"  v-if="  item.state == 0 || item.state == 3">
                <button class="btn refuse" @click="refuse(item)">拒绝</button>
                <button class="btn blue" @click="agree(item)">同意</button>
              </view>
            </view>
          </view>
        </view>
        <!-- 正在加载组件 -->
        <view>
          <s-loadmore-gather :current_page="listPage" :last_page="listlast_page" ref="loadmoreRef"></s-loadmore-gather>
        </view>
      </scroll-view>

      <u-empty v-else mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" text="暂无内容" marginTop="50%"></u-empty>
    </view>





    <!-- 底部占位盒子 -->
    <view v-if="state.status == '0,3'">
      <view class="end_box" v-if="personLength !== 0">
        <!-- 全选按钮盒子 -->
        <view class="check_all_box">
          <!-- 全选按钮 -->
          <view class="check_all_button" @tap="checkAllInteraction">
            <view class="select_image">
              <image v-if="checkAll === true" :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_check.png`" mode="scaleToFill" />
              <image v-else :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_checkfor.png`" mode="scaleToFill" />
            </view>
            <view>全选</view>
          </view>
        </view>
        <view class="placeholder"></view>
        <!-- 底部保存按钮 -->
        <view>
          <s-button @leftNetWork="nextBackTowForm" @rightNetWork="nextTowForm" :leftWidth="'30%'" :rightWidth="'70%'" :type="'twobutton'" :oneText="'拒绝'" :twoText="'同意'" />
        </view>
      </view>
    </view>
    





  </s-layout>
  <!-- 拒绝理由 -->
  <s-reasons-comfirm :show="showRefuse" @cancel="reasonsCancel" @affirm="reasonsConfirm"></s-reasons-comfirm>
</template>

<script setup>
import { baseUrl } from '@/sheep/config';
import sheep from '@/sheep';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, reactive } from 'vue';
import { formatDate } from '@/utils/fn.js';
const { safeAreaInsets } = uni.getSystemInfoSync()
const userInfo = sheep.$store('user').userInfo;
const state = ref({
  bgColor: '#fff',
  menulist: [
    { name: '待审批', value: '0,3', badge: 0 },
    // { name: '待审批', value: '0', badge: 0 },
    { name: '已审批', value: '1' },
    { name: '已拒绝', value: '2' },
    { name: '审批中', value: '3' },
  ],
  currentTab: 0,
  status: '0,3',
  arrclass:['yellow','green','red','blue','gray']
})
//点击切换菜单  
const menulistclick = (item) => {
  list.value = [];
  checkAll.value = false
  selectedIds.value = []
  state.value.status = item.value;
  listpagenumber.value = 1;
  getListDetail()
}
const list = ref([])
const listPage = ref()
const listlast_page = ref();
const listpagenumber = ref(1);
onLoad((options) => {
  list.value = [];
  listpagenumber.value = 1;
  getListDetail()
})


// 1.
const loadmoreRef = ref()
//数据请求
const personLength = ref()
const getListDetail = () => {
  let obj = {
    state: state.value.status,
  };
  let state_op = '=';
  if(state.value.status == '0,3') {
    state_op = 'in';
  }
  let params = {
    filter: JSON.stringify(obj),
    op: JSON.stringify({
      state: state_op,
    }),
    page: listpagenumber.value,
    with: 'user'
  };
  sheep.$api.borrowing.getBorrowingProjectApproveList(params).then((res) => {
    list.value = [...list.value, ...res?.data.rows];
    listPage.value = res.data.current_page
    listlast_page.value = res.data.last_page
    if(state.value.status == '0,3') {
        state.value.menulist[0].badge = res.data.total
      }
      personLength.value = res.data.total
      return personLength.value
  });
}
//滚动触底
const listScrolltolower = () => {
  loadmoreRef.value.PopupScrolltolower()
  if (listPage.value < listlast_page.value) {
    listpagenumber.value += 1;
    checkAll.value = false
    selectedIds.value = []
    list.value.forEach(item => {
      item.is_selected = false
    })
  } else {
    return;
  }
  getListDetail();
};
const lookDetail = (item) => {
  sheep.$router.go('/subpackage/user/user/user_borrowing/user_borrowing_detail', {
    ids: item.id,
    page:'approval'
  });
}
//同意
const agree = (item) => {

  let params = {
    ids: item.id 
  }
  agreeList(params)
}

const agreeList = (params)=>{
  uni.$u.throttle(() => {
    // #ifdef MP
    sheep.$platform.useProvider('wechat').subscribeMessage('apply_notice');
    // #endif
    sheep.$api.borrowing.getBorrowingProjectPass(params).then((res) => {
      sheep.$helper.toast(res.msg);
      if (res.code == 1) {
        setTimeout(function () {
          list.value = [];
          listpagenumber.value = 1;
          checkAll.value = false
            selectedIds.value = []
          getListDetail();
        }, 1000);
      }
    });
  }, 1000);
}

// 拒绝
const showRefuse = ref(false)
const reasonsValue = ref()
const reasonsId = ref()
const refuse = (item) => {
  showRefuse.value = true
  reasonsId.value = item.id
}
//拒绝理由 确定 -->
const reasonsConfirm = (e) => {
  uni.$u.throttle(() => {
    // #ifdef MP
    sheep.$platform.useProvider('wechat').subscribeMessage('apply_result_notice');
  // #endif
  reasonsValue.value = e
  if (!reasonsValue.value) {
    sheep.$helper.toast('请输入拒绝理由');
    return
  } else {
    let params = {
      ids: reasonsId.value || selectedIds.value,
      reasons: reasonsValue.value
    }
    sheep.$api.borrowing.getBorrowingProjectRefuse(params).then((res) => {
      reasonsCancel()
      sheep.$helper.toast(res.msg);
      if (res.code == 1) {
        setTimeout(function () {
          list.value = [];
          listpagenumber.value = 1;
          checkAll.value = false
          selectedIds.value = []
          getListDetail();
        }, 1000);
      }
    });
  }
}, 1000)
}
// 拒绝理由取消
const reasonsCancel = (e) => {
  showRefuse.value = e
  reasonsValue.value = ''
}
// 页面下拉刷新
const freshing = ref(false)
const triggered = ref(false)
const isOpenRefresh = ref(true)  // 是否开启下拉
// 自定义下拉刷新控件被下拉
const onPulling = (e) => {
  if (e.detail.deltaY < 0) return  // 防止上滑页面也触发下拉
  triggered.value = true;
}
// 自定义下拉刷新被触发
const onRefresh = () => {
  if (freshing.value) return;
  freshing.value = true;
  setTimeout(() => {
    triggered.value = false;
    freshing.value = false;
    list.value = [];
    listpagenumber.value = 1;
    checkAll.value =false
    selectedIds.value =[]
    getListDetail();
  }, 500);
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = 'restore'; // 需要重置
  // console.log("onRestore");
}
// 自定义下拉刷新被中止
const onAbort = () => {
  // console.log("onAbort");
}

// 全选
const checkAll = ref(false)
const selectedIds = ref([])
// 全选交互逻辑
const checkAllInteraction = () => {
  selectedIds.value = []
  if (checkAll.value === false) {
    list.value.forEach(item => {
      selectedIds.value.push(item.id);
      item.is_selected = true
    });
  } else {
    list.value.forEach(item => {
      item.is_selected = false
    });
  }
  checkAll.value = !checkAll.value
}
// 多选  total.value 总共多少条数据

const moreSelect = (item) => {
  item.is_selected = !(item?.is_selected)
  const index = selectedIds.value.indexOf(item.id);
  if (index === -1) {
    selectedIds.value.push(item.id);
    if (selectedIds.value.length == personLength.value) {
      checkAll.value = true
    }
  } else {
    selectedIds.value.splice(index, 1);
    if (selectedIds.value.length !== personLength.value) {
      checkAll.value = false
    }
  }
}
//全选拒绝
const nextBackTowForm = () => {
  if (selectedIds.value.length == 0) {
    sheep.$helper.toast('请选择待审批内容')
  } else {
    showRefuse.value = true
  }
}
// 全选同意
const nextTowForm = () => {
  if (selectedIds.value.length == 0) {
    sheep.$helper.toast('请选择待审批内容')
  } else {
    let params={
      ids:selectedIds.value
    }
    agreeList(params)
  }
}



</script>
<style lang="scss" scoped>
@import '../compentns/publiclist.scss';

// 滚动
.comprehensive {
  width: calc(100% - 40rpx);
  background-color: rgba(0, 0, 0, 0);
  margin: 0 20rpx;
  height: calc(82vh - 244rpx);
}

.time_money {
  color: #666666;
  font-weight: 500;
 font-size:$uni-font-size-26;
  margin-right: 16rpx;
}

.time_name {
  font-family: PingFangSC;
  color: #FF6600 !important;
  font-weight: 500;
 font-size:$uni-font-size-26;
}

.item_left {
  .item_left_box {
    margin-bottom: 10rpx !important;
    .name{
      white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
    }
  }
}

.item {
  padding-bottom: 10rpx;

  .item_left_box {
    margin-bottom: 10rpx !important;
  }

  .flex {
    align-items: center !important;
  }

  .item_left {
    width: 55% !important;
  }

  .item_right {
    padding-right: 10rpx !important;
  }
}


// 选择盒子
.select_box {
  display: flex;
  align-items: center;
}
  // 选择图标
.select_image {
  width: 30rpx;
  height: 30rpx;
  margin:0 0 0 22rpx;
  image {
    width: 100%;
    height: 100%;
  }
}
// 末尾盒子 (此盒子没有  “父相 ” 如要改动请按需更改)
.end_box {
  position: fixed;
  bottom: 0;
  z-index: 98;
  height: 244rpx;
  width: 100%;

  // 全选按钮盒子
  .check_all_box {
    height: 80rpx;
    width: 100%;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    border: 2rpx solid #efefef;

    // 全选按钮
    .check_all_button {
      display: flex;
      margin-left: 52rpx;
      align-items: center;
      font-family: PingFangSC;
      color: #0239f7;
      font-weight: $uni-font-weight;
      font-size: $uni-font-size-base;
      font-style: normal;
      text-decoration: none;
    }

    // 已选择
    .selected_box {
      display: flex;
      margin-right: 40rpx;
      align-items: center;
      font-family: PingFangSC;
      color: $uni-text-color;
      font-weight: $uni-font-weight;
      font-size: $uni-font-size-base;
      font-style: normal;
      text-decoration: none;
    }
  }
.supervisor_state{
  display: flex;
  margin-left: 52rpx;
  align-items: center;
  font-family: PingFangSC;
  color: #0239f7;
  font-weight: $uni-font-weight;
  font-size: $uni-font-size-base;
  font-style: normal;
  text-decoration: none;
}
  // 占位盒子
  .placeholder {
    height: 32rpx;
    width: 100%;
    background-color: #ffffff;
  }
}

// 全选图标
.select_image {
  width: 30rpx;
  height: 30rpx;
  margin-right: 22rpx;
  image {
    width: 100%;
    height: 100%;
  }
}

</style>